package sing.core.ext

import android.app.Activity
import android.app.Dialog
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import sing.core.R

//loading框
private var loadingDialog: Dialog? = null

/**
 * 打开等待框
 */
fun AppCompatActivity.showLoadingExt(message: String = "") {
    if (!this.isFinishing) {
        if (loadingDialog == null) {
            loadingDialog = Dialog(this)
            val window = loadingDialog!!.window
            val params = window?.attributes
            params?.gravity = Gravity.CENTER
            window?.setBackgroundDrawableResource(android.R.color.transparent)
            window?.setDimAmount(0f) // 去除遮罩
            window?.attributes = params

            val view = LayoutInflater.from(this).inflate(R.layout.layout_loading_dialog,null,false)
            loadingDialog!!.setContentView(view)
            loadingDialog!!.setCancelable(true)
            loadingDialog!!.setCanceledOnTouchOutside(false)
            if (!isFinishing){
                loadingDialog?.show()
            }

            if (message.isEmpty()){
                view.findViewById<TextView>(R.id.loading_tips).visibility = View.GONE
            }else{
                view.findViewById<TextView>(R.id.loading_tips).visibility = View.VISIBLE
                view.findViewById<TextView>(R.id.loading_tips).text = message
            }
        }
        if (!isFinishing){
            loadingDialog?.show()
        }
    }
}


/**
 * 关闭等待框
 */
fun Activity.dismissLoadingExt() {
    loadingDialog?.dismiss()
    loadingDialog = null
}

/**
 * 等待框是否show
 */
fun Activity.isShowing():Boolean {
    if (loadingDialog == null){
        return false
    }
    return loadingDialog!!.isShowing
}


/**
 * 倒计时的实现
 */
fun FragmentActivity.countDown(
    time: Int = 5,
    timeMillis: Long = 1000,
    start: (scop: CoroutineScope) -> Unit,
    end: () -> Unit,
    next: (time: Int) -> Unit
) {
    lifecycleScope.launch {
        // 在这个范围内启动的协程会在Lifecycle被销毁的时候自动取消
        flow {
            (time downTo 0).forEach {
                delay(timeMillis)
                emit(it)
            }
        }.onStart { // 倒计时开始 ，在这里可以让Button 禁止点击状态
            start(this@launch)
        }.onCompletion { // 倒计时结束 ，在这里可以让Button 恢复点击状态
            end()
        }.collect {
            next(it)
        }
    }
}